import { useQuery } from '@tanstack/react-query'
import { Card, Row, Col, Spin, Table } from 'antd'
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts'
import { getStatistics } from '../api/gateway'

export default function Monitoring() {
  const { data: statistics, isLoading } = useQuery({
    queryKey: ['statistics'],
    queryFn: getStatistics,
    refetchInterval: 5000,
  })

  // 处理请求趋势数据，添加错误数
  const requestData = (statistics?.request_trend || []).map((item: any) => ({
    time: item.time,
    requests: item.requests,
    errors: item.errors || 0,
  }))

  // 生成延迟数据（基于统计数据）
  const latencyP50 = statistics?.latency?.p50 || 0
  const latencyP95 = statistics?.latency?.p95 || 0
  const latencyP99 = statistics?.latency?.p99 || 0
  
  const latencyData = [
    { time: '当前', p50: latencyP50, p95: latencyP95, p99: latencyP99 },
  ]

  // 使用真实的热门路由数据
  const topRoutesData = (statistics?.top_routes || []).map((route: any) => ({
    route: route.route,
    requests: route.requests,
    errors: route.errors || 0,
    avgLatency: route.avg_latency || 0,
  }))

  if (isLoading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    )
  }

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>监控面板</h1>
      <Row gutter={[16, 16]}>
        <Col xs={24}>
          <Card title="请求趋势">
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={requestData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Area
                  type="monotone"
                  dataKey="requests"
                  stroke="#1890ff"
                  fill="#1890ff"
                  fillOpacity={0.6}
                />
                <Area
                  type="monotone"
                  dataKey="errors"
                  stroke="#ff4d4f"
                  fill="#ff4d4f"
                  fillOpacity={0.6}
                />
              </AreaChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24}>
          <Card title="响应延迟（P50/P95/P99）">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={latencyData.length > 0 ? latencyData : [{ time: '当前', p50: 0, p95: 0, p99: 0 }]}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line
                  type="monotone"
                  dataKey="p50"
                  stroke="#52c41a"
                  strokeWidth={2}
                />
                <Line
                  type="monotone"
                  dataKey="p95"
                  stroke="#faad14"
                  strokeWidth={2}
                />
                <Line
                  type="monotone"
                  dataKey="p99"
                  stroke="#ff4d4f"
                  strokeWidth={2}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24}>
          <Card title="热门路由统计">
            <Table
              dataSource={topRoutesData}
              columns={[
                { title: '路由', dataIndex: 'route', key: 'route' },
                { title: '请求数', dataIndex: 'requests', key: 'requests' },
                { title: '错误数', dataIndex: 'errors', key: 'errors' },
                {
                  title: '平均延迟 (ms)',
                  dataIndex: 'avgLatency',
                  key: 'avgLatency',
                },
              ]}
              pagination={false}
            />
          </Card>
        </Col>
      </Row>
    </div>
  )
}

